package com.cn.qgx428.orderingmeal;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.qgx428.orderingmeal.adapter.CarAdapter;
import com.cn.qgx428.orderingmeal.dialog.PayDialog;
import com.cn.qgx428.orderingmeal.layout.CarRecyclerView;
import com.cn.qgx428.orderingmeal.myClass.Car;
import com.cn.qgx428.orderingmeal.myClass.MyKeyInfo;
import com.cn.qgx428.orderingmeal.myClass.Order;
import com.cn.qgx428.orderingmeal.myClass.User;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class CarActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG ="CarActivity";

    private MyKeyInfo keyInfo;

    private ImageView backbtn;

    private LinearLayout hasFoodLayout;
    private LinearLayout notHasFoodLayout;

    /**
     * 用于根据购物车有无数据显示不同的页面
     */
    private static int HAS_FOOD = 0;
    private static int NOT_HAS_FOOD = 1;
    private int FOOD_DATA = NOT_HAS_FOOD;

    private CarRecyclerView recyclerView;
    private List<Car> car;
    private CarAdapter adapter;

    private TextView total;
    private TextView pay;

    /**
     *根据用户是否支付处理不同逻辑
     */
    private static final int PAIED = 0;
    private static final int NOT_PAY = 1;
    private int IS_PAY = NOT_PAY;

    /**
     * 用户支付密码状态，拥有，未拥有
     */
    private static final int HAS_PAY_PASSWORD = 0;
    private static final int SET_PAY_PASSWORD = 1;
    private int PAY_STATE = HAS_PAY_PASSWORD;

    private String userPayPassword = null;

    /**
     * 判定有无选取食物
     */
    private static final Boolean NOT_FOOD_BE_CHECK = false;
    private static final Boolean HAS_FOOD_BE_CHECK = true;
    private Boolean FOOD_BE_CHECK = NOT_FOOD_BE_CHECK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car);

        init();
        getData();
    }

    /**
     * 获取购物车食物列表
     * 根据是否有数据显示不同页面
     */
    private void getData() {
        String userID = keyInfo.getUserID();
        BmobQuery<Car> query = new BmobQuery<Car>();
        query.addWhereEqualTo("userID",userID);
        query.include("food");
        query.findObjects(new FindListener<Car>() {
            @Override
            public void done(List<Car> list, BmobException e) {
                if (e == null){
                    if (list.size()>0){
                        FOOD_DATA = HAS_FOOD;
                    } else {
                        FOOD_DATA = NOT_HAS_FOOD;
                    }
                    car = list;
                    showMainLayout(FOOD_DATA);
                }
            }
        }) ;
    }

    private void showMainLayout(int food_data) {
        if (food_data == NOT_HAS_FOOD){
            hasFoodLayout.setVisibility(View.GONE);
            notHasFoodLayout.setVisibility(View.VISIBLE);
        } else if (food_data == HAS_FOOD){
            hasFoodLayout.setVisibility(View.VISIBLE);
            notHasFoodLayout.setVisibility(View.GONE);
            adapter = new CarAdapter(this,car,R.layout.car_fooditem);
            setAdapter();

            recyclerView.setAdapter(adapter);
            recyclerView.setOnItemClickListenre(new CarRecyclerView.OnItemClickListener() {
                @Override
                public void onClick(View view, final int position) {
                    Car DCar = new Car();
                    DCar.setObjectId(car.get(position).getObjectId());
                    DCar.delete(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null){
                                car.remove(position);
                                adapter.removeData(position);
                                adapter.notifyItemRemoved(position);
                            } else {
                                Toast.makeText(CarActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                                Log.d(TAG, "删除食物 ："+e.getErrorCode()+e.getMessage());
                            }
                        }
                    });
                }
            });

        }
    }

    /**
     * 设置适配器数据初始时和变化时的控件事件
     */
    private void setAdapter() {
        adapter.setFoodCheckListener(new CarAdapter.OnItemCheckListener() {
            @Override
            public void onItemChecked(int position) {
                //Toast.makeText(CarActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
                total.setText(adapter.getTotalPrice());
                FOOD_BE_CHECK = adapter.isHasFoodChecked();
            }
        });

        adapter.setItemAmountChangedListener(new CarAdapter.OnItemAmountChangedListener() {
            @Override
            public void onAmountChanged(int position) {
                total.setText(adapter.getTotalPrice());
            }
        });
    }

    private void init() {
        keyInfo = (MyKeyInfo) getIntent().getSerializableExtra("keyInfo");

        backbtn = (ImageView)findViewById(R.id.car_back);
        backbtn.setOnClickListener(this);

        hasFoodLayout = (LinearLayout)findViewById(R.id.car_hasFoodLayout);
        notHasFoodLayout = (LinearLayout)findViewById(R.id.car_haveNotFoodLayout);

        recyclerView = (CarRecyclerView) findViewById(R.id.car_foddRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        total = (TextView)findViewById(R.id.car_sum);
        pay = (TextView)findViewById(R.id.car_pay);
        pay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.car_back:
                finish();
                break;
            case R.id.car_pay:
                userPayFor();
                break;
        }
    }

    private void userPayFor() {
        //支付前先选定食物
        if (FOOD_BE_CHECK){
            //获取服务器上的用户支付密码
            if (userPayPassword == null){
                BmobQuery<User> query = new BmobQuery<User>();
                query.getObject(keyInfo.getUserID(), new QueryListener<User>() {
                    @Override
                    public void done(User user, BmobException e) {
                        if (e == null){
                            userPayPassword = user.getPayPassword();

                            if (userPayPassword == null){
                                PAY_STATE = SET_PAY_PASSWORD;
                            }

                            showPayDialog();

                        } else {
                            Log.d(TAG, "获取用户支付密码："+e.getErrorCode()+e.getMessage());
                        }
                    }
                });
            }else{
                showPayDialog();
            }
        } else{
            Toast.makeText(this, "请选定食物", Toast.LENGTH_SHORT).show();
        }


    }

    private void showPayDialog() {
        final PayDialog dialog = new PayDialog(this , userPayPassword, keyInfo.getUserID());
        dialog.setSureClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!dialog.isChooseCard()){
                    Toast.makeText(CarActivity.this, "请先选择支付的银行卡", Toast.LENGTH_SHORT).show();
                }else{
                    //获取用户输入的支付密码
                    final String payPassword = dialog.getPassword();
                    if (payPassword.length() < 6){
                        Toast.makeText(CarActivity.this, "支付密码长度不足6位", Toast.LENGTH_SHORT).show();
                    } else{
                        //用户无支付密码，设置支付密码
                        if (PAY_STATE == SET_PAY_PASSWORD){
                            //更新用户支付密码数据
                            User user = new User();
                            user.setObjectId(keyInfo.getUserID());
                            user.setPayPassword(payPassword);
                            user.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null){
                                        userPayPassword = payPassword;
                                        Toast.makeText(CarActivity.this, "设置支付密码成功", Toast.LENGTH_SHORT).show();
                                        dialog.dismiss();
                                        PAY_STATE = HAS_PAY_PASSWORD;
                                        showPayDialog();
                                    } else {
                                        Toast.makeText(CarActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                                        Log.d(TAG, "设置支付密码 ："+e.getErrorCode()+e.getMessage());
                                    }
                                }
                            });
                        } else if(PAY_STATE == HAS_PAY_PASSWORD){
                            if (userPayPassword.equals(payPassword)){
                                IS_PAY = PAIED;
                                dialog.dismiss();
                                createOrder(IS_PAY);
                            } else {
                                IS_PAY = NOT_PAY;
                                Toast.makeText(CarActivity.this, "支付密码错误", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            }
        });
        dialog.show();
    }

    private void createOrder(int pay) {
        if (pay == NOT_PAY){
            return;
        }
        final List<BmobObject> DCars = new ArrayList<BmobObject>(); //生成订单后删除的购物车数据
        List<Boolean> options = adapter.getOptions();
        List<Double> totalPrice = adapter.getItemTotalPrice();
        String foodsID = "";
        String itemTotalPrice = "";

        for(int i=0; i<options.size(); i++){
            if (options.get(i) == true){
                foodsID+= car.get(i).getFood().getObjectId() + ",";
                itemTotalPrice += totalPrice.get(i)+ ",";
                Car c = new Car();
                c.setObjectId(car.get(i).getObjectId());
                DCars.add(c);
            }
        }
        //用户信息
        User user = new User();
        user.setObjectId(keyInfo.getUserID());
        Order order = new Order();
        order.setUser(user);
        order.setFoodsID(foodsID);
        order.setItemTotalPrice(itemTotalPrice);
        order.setTotalPrice(adapter.getTotalPriceOfDouble());
        order.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Toast.makeText(CarActivity.this, "下单成功", Toast.LENGTH_SHORT).show();
                    //下单成功推送消息
                    sendMassage(String.valueOf(adapter.getTotalPriceOfDouble()),s);
                    new BmobBatch().deleteBatch(DCars).doBatch(new QueryListListener<BatchResult>() {
                        @Override
                        public void done(List<BatchResult> list, BmobException e) {
                            if (e == null){

                            } else {
                                Log.d(TAG, "下单后删除购物车数据："+e.getErrorCode()+e.getMessage());
                            }
                        }
                    });

                    Intent intent = new Intent(CarActivity.this, OrderActicity.class);
                    intent.putExtra("keyInfo",keyInfo);
                    startActivity(intent);
                    finish();
                } else{
                    Toast.makeText(CarActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "付款操作 :"+e.getErrorCode()+e.getMessage());
                }
            }
        });
    }

    private void sendMassage(String totalPrice , String orderID) {
        Intent intent = new Intent(this,OrderDetail.class);
        intent.putExtra("userID",keyInfo.getUserID());
        intent.putExtra("orderID",orderID);
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("您成功下单，并支付"+totalPrice+"元")
                .setContentText("点击查看详情")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.massage_icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.massage_icon))
                .setContentIntent(pi)
                .setAutoCancel(true)
                .build();
        manager.notify(1,notification);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
